const Redis = require("ioredis");
const { Store } = require("koa-session2");
const nodeEnv = process.env.NODE_ENV;
const redisConfig = require('../utils/config')[nodeEnv].redis;
 
class RedisStore extends Store {
    constructor() {
        super();
        this.redis = new Redis(redisConfig);
    }
 
    async get(sid, ctx) {
        let data = await this.redis.get(`SESSION:${sid}`);
        return JSON.parse(data);
    }
 
    async set(session, { sid =  this.getID(24), maxAge = redisConfig.ttl } = {}, ctx) {
        try {
            // Use redis set EX to automatically drop expired sessions
            await this.redis.set(`SESSION:${sid}`, JSON.stringify(session), 'EX', maxAge);
        } catch (e) {}
        return sid;
    }
 
    async destroy(sid, ctx) {
        return await this.redis.del(`SESSION:${sid}`);
    }
}
 
module.exports = RedisStore;